﻿using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using System.Linq;
using PmSadis.Dal;
using System;
using System.Data.Entity;

namespace PmSadis.Repositories
{
    /// <summary>
    /// Хранилище материалов справочных работ
    /// </summary>
    public class WorkMaterialRepository : IListRepository<WorkMaterial>
    {
        private ModelsContext _context = new ModelsContext();

        /// <summary>
        /// Полный список материалов
        /// </summary>
        public IQueryable<WorkMaterial> All
        {
            get
            {
                return _context.WorkMaterials;
            }
        }

        /// <summary>
        /// Удалить материал
        /// </summary>
        /// <param name="id">Идентификатор материала</param>
        public void Delete(object id)
        {
            var workMaterialId = (int)id;
            var workMaterial = _context.WorkMaterials.FirstOrDefault(x => x.WorkMaterialId == workMaterialId);
            if (workMaterial == null) return;

            _context.WorkMaterials.Remove(workMaterial);
            _context.SaveChanges();
        }

        /// <summary>
        /// Создать или редактировать материал
        /// </summary>
        /// <param name="workMaterial">Mатериал</param>
        public object Edit(WorkMaterial workMaterial)
        {
            var dateNow = DateTime.Now;
            if (workMaterial.WorkMaterialId == 0)
            {
                workMaterial.DateCreate = dateNow;
                workMaterial.DateUpdate = dateNow;
                _context.Entry(workMaterial).State = EntityState.Added;
            }
            else
            {
                workMaterial.DateUpdate = dateNow;
                _context.Entry(workMaterial).State = EntityState.Modified;
            }

            _context.SaveChanges();

            return workMaterial.WorkMaterialId;
        }
    }
}
